﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Common.EntityValidation
{
    public class EntifyValidator
    {
        public static ValidResult Validate(object data, params string[] ignore) //验证完所有字段
        {
            return new EntifyValidator().Verify(false, data, ignore);
           
        }
        public static ValidResult ValidateQuickly(object data, params string[] ignore)  //当有未通过的验证时，直接返回，停止验证
        {

            return   new EntifyValidator().Verify(true, data, ignore);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="quickly">验证完所有字段Or验证到未通过的立即返回</param>
        /// <param name="data">需要验证的数据</param>
        /// <param name="ignore">忽略的字段</param>
        /// <returns></returns>
        public virtual ValidResult Verify(bool quickly, object data, params string[] ignore)
        {


            ValidResult result = new ValidResult();

            List<PropertyInfo> props = data.GetType().GetProperties().Where(a => !ignore.Contains(a.Name.ToLower())).ToList();



            foreach (var item in props)
            {
                var validateattrs = item.GetCustomAttributes(typeof(ValidationAttribute));//

                var input = item.GetValue(data);

                foreach (var itemattr in validateattrs)
                {
                    var attr = ((ValidationAttribute)itemattr);
                    if (attr != null)
                    {
                        attr.Name = item.Name;
                        var isvalid = attr.Verify(input);

                        if (!isvalid)
                        {
                            ValidResultDetail validResultDetail = new ValidResultDetail();
                            validResultDetail.Name = item.Name;
                            validResultDetail.ErrorMessage = string.Format(attr.ErrorMessage, item.Name);
                            validResultDetail.IsValid = false;
                            result.ValidResultDetails.Add(validResultDetail);
                            if(quickly)
                            {
                                return result;
                            }
                        }
                    }
                }
            }

            return result;
        }
    }
}
